<template>
	<view class="pages_intelligence" :style="{paddingTop: `${search.height+search.top+10}px`}">
		<myTabs :title="title" :isTrue="isText || isText==0" @goBlack="goBlack" :mybackgroundColor="'#fff'"></myTabs>
		<view class="cityBox" :style="{top: `${search.height+search.top+10}px`}">
			<view class="cityHeard" id="cityHeard">
				<view class="" v-if="!isText">

					<view class="cityHeard_title">请选择要加入的社群城市</view>
					<view class="cityHeard_text">如无您所在城市，建议您选择所处省份省会城市。</view>

				</view>
				<input class="cityHeard_input" @confirm="confirm" placeholder="城市搜索" />
				<view class="cityHeard_bottonBox">
					<view class="cityHeard_bottonBoxLeft">当前定位城市</view>
					<view class="cityHeard_bottonBoxRight" @click="goLocation">
						<span>{{locationCity?locationCity:'点击授权定位'}}</span>
						<image src="/static/img/danqianIcon.png"></image>
					</view>
				</view>
			</view>

			<view class="indexListBox"
				:style="{height : `calc(100vh - ${search.height+search.top+10}px - ${contentHeight}px)`}">
				<u-index-list :index-list="indexList">
					<template v-for="(item, newindex) in itemArr">
						<u-index-item>
							<u-index-anchor :text="indexList[newindex]"></u-index-anchor>
							<view @click="changIndex(newindex,index,cell.name)"
								:class="(listIndex[1] == index)&&(newindex == listIndex[0]) ? 'list-cell listAct' : 'list-cell'"
								v-for="(cell, index) in item">
								<span>{{cell.name}}</span>
								<image v-if="(listIndex[1] == index)&&(newindex == listIndex[0])"
									src="/static/img/activateIcon.png"></image>
							</view>
						</u-index-item>
					</template>
				</u-index-list>
			</view>

		</view>
		<view :class="listIndex[1]!=undefined? 'ensureButton' : 'noEnsureButton'" @click="ensure">
			确定选择
		</view>
	</view>

</template>

<script>
	import myTabs from "@/components/myTabs/index.vue"
	export default {
		components: {
			myTabs
		},
		data() {
			return {
				listIndex: [''],
				contentHeight: 0,
				title: '社群城市选择',
				indexList: ["A", "B", "C", "D"],
				itemArr: [
					['鞍山', '安庆'],
					['北京', '保定', '蚌埠', '包头'],
					['成都', '重庆', '长沙', '长春'],
					['D', 'D1', 'D2', 'D3']
				],
				city: '广州市',
				cityTure: '广州市',
				cityUrban: [],
				isText: 0,
				locationCity: '',
				isBlack: 0,
				priceId: 0,
				isPast: false,
				pastTime: 1000 * 60 * 60 * 24 * 7

			}
		},
		onLoad(oprtions) {
			// #ifndef H5
			let search = uni.getMenuButtonBoundingClientRect()
			this.$store.commit('updataSearch', search);
			// #endif
			let locationCity = uni.getStorageSync('locationCity');
			this.locationCity = locationCity ? locationCity.name : ''

			if (!this.location) {
				this.getLocation();
			} else {
				this.initCity();
			}
			if (oprtions.isBlack) {
				this.isBlack = oprtions.isBlack;
			}
			if (oprtions.priceId) {
				this.priceId = oprtions.priceId;
			}

			if (oprtions.isText) {
				this.isText = oprtions.isText;

			}
			if (oprtions.isPast) {
				this.isPast = oprtions.isPast;

			}

		},
		onReady() {
			const query = uni.createSelectorQuery().in(this);
			query.select("#cityHeard").boundingClientRect(data => {
				this.contentHeight = data.height;
			}).exec();
		},
		computed: {
			search() {
				return this.$store.state.search;
			},
			location() {
				return this.$store.state.location;
			},
			user() {
				return this.$store.state.user;
			},
		},
		methods: {
			uzzyQuery(list, keyWord) {
				var reg = new RegExp(keyWord, 'ig');

				if (!keyWord) {
					return list;
				}
				var arr = [];

				for (var i = 0; i < list.length; i++) {
					let item = list[i].regionList
					for (var j = 0; j < item.length; j++) {
						if (reg.test(item[j].name)) {
							arr.push({
								first: list[i].first,
								regionList: item
							});
						}
					}
				}

				return arr;
			},
			confirm(e) {
				let value = e.detail.value.trim();
				let nowCityUrban = this.uzzyQuery(this.cityUrban, value);

				this.indexList = [];
				this.itemArr = [];
				this.listIndex = [];

				nowCityUrban.forEach((item, index) => {
					this.indexList.push(item.first);
					item.regionList.forEach((nowItem, nowIndex) => {
						if (nowItem.name == this.city) {
							this.listIndex = [index, nowIndex]
						}
					});
				});

				this.indexList.forEach((item, index) => {
					if (nowCityUrban[index]) {
						this.itemArr = [...this.itemArr, nowCityUrban[index].regionList];
					}

				})

			},
			initLocation() {
				let that = this;
				let location = uni.getStorageSync('location')
				if (!location) {
					this.getLocation();
				} else {
					this.city = location.name;
					uni.hideLoading()
				}

			},
			setUserLocation(city, type) {
				return new Promise((ress, rejj) => {
					this.$api.userLocation({
						city
					}).then(res => {
						if (res.code == 200) {
							uni.setStorageSync('location', res.data.location);
							this.$store.commit('updatalocation', res.data
								.location);
							this.$store.commit('updataUser', res.data
								.user);
							if (type) {
								this.locationCity = res.data.location.name;
								console.log('res.data.location', res.data.location)
								uni.setStorageSync('locationCity', res.data.location);
							}
							this.city = this.cityTure = res.data.location.name;
							this.listIndex = []

							this.cityUrban.forEach((item, index) => {
								this.indexList.push(item.first);
								item.regionList.forEach((nowItem, nowIndex) => {
									if (nowItem.name == this.city) {
										this.listIndex = [index, nowIndex]
									}
								});
							});

							this.indexList.forEach((item, index) => {
								if (this.cityUrban[index]) {
									this.itemArr = [...this.itemArr, this.cityUrban[index]
										.regionList
									];
								}

							})

							this.initLocation();


							ress();
							uni.hideLoading()
						}
					})
				})

			},
			getLocation(type) {
				return new Promise((ress, rejj) => {
					let that = this;
					uni.getFuzzyLocation({
						type: 'gcj02', //返回可以用于uni.openLocation的经纬度
						success: (res) => {
							this.$qqmapsdk.reverseGeocoder({
								//把你的经纬度
								location: {
									latitude: res.latitude,
									longitude: res.longitude
								},
								success(qqmapsdkRes) {
									let city = qqmapsdkRes.result.address_component.city
										.replace('市', '');
									// that.setUserLocation(city,type);
									that.$api.userLocation({
										city
									}).then(res => {
										if (res.code == 200) {
											uni.setStorageSync('location', res.data
												.location);
											that.$store.commit('updatalocation', res
												.data
												.location);
											that.$store.commit('updataUser', res.data
												.user);


											that.city = that.cityTure = res.data
												.location.name;
											that.listIndex = []

											that.cityUrban.forEach((item, index) => {
												that.indexList.push(item
													.first);
												item.regionList.forEach((
													nowItem, nowIndex
												) => {
													if (nowItem.name ==
														that.city) {
														that.listIndex = [
															index,
															nowIndex
														]
													}
												});
											});

											that.indexList.forEach((item, index) => {
												if (that.cityUrban[index]) {
													that.itemArr = [...that
														.itemArr, that
														.cityUrban[index]
														.regionList
													];
												}

											})
											if (type) {
												console.log('locationCity--->', res
													.data.location)
												uni.setStorageSync('locationCity', res
													.data.location);
												that.locationCity = res.data.location
													.name;

												if (!that.isBlack) {
													let pages = getCurrentPages();
													let prevPage = pages[pages.length -
														2];
													prevPage.onShow(true);
													uni.navigateBack();
												} else {
													that.ensure()
												}

											}
											uni.hideLoading()
										}
									})


								}
							})
						},
						fail() {
							that.indexList = [];
							that.itemArr = [];
							that.$api.regionRegionList().then(res => {
								if (res.code == 200) {
									that.cityTure = that.city = '成都';
									that.cityUrban = res.data;
									that.listIndex = [];
									res.data.forEach((item, index) => {
										that.indexList.push(item.first);
										item.regionList.forEach((nowItem, nowIndex) => {
											if (nowItem.name == '成都') {
												that.listIndex = [index, nowIndex];
											}

										});
									});
									that.indexList.forEach((item, index) => {
										that.itemArr = [...that.itemArr, res.data[index]
											.regionList
										];
									});
								}
							})
							uni.hideLoading()
						}
					});
				})

			},
			initCity() {
				this.indexList = [];
				this.itemArr = [];
				this.listIndex = []
				uni.showLoading({
					title: '加载中',
					icon: 'none',
					mask: true
				})
				this.$api.regionRegionList().then(res => {
					if (res.code == 200) {
						this.cityTure = this.city = this.location.name;
						this.cityUrban = res.data;
						res.data.forEach((item, index) => {
							this.indexList.push(item.first);
							item.regionList.forEach((nowItem, nowIndex) => {
								if (nowItem.name == this.city) {
									this.listIndex = [index, nowIndex]
								}
							});
						});
						this.indexList.forEach((item, index) => {
							this.itemArr = [...this.itemArr, res.data[index].regionList];
						})
						this.initLocation();
					}
				})
			},
			goLocation() {
				console.log(this.locationCity)
				if (this.locationCity) {
					this.setUserLocation(this.locationCity).then(res => {
						if (!this.isBlack) {
							let pages = getCurrentPages();
							let prevPage = pages[pages.length - 2];
							prevPage.onShow(true);
							uni.navigateBack();
						} else {
							this.ensure()
						}

					})

				} else {
					let that = this;
					uni.openSetting({
						success(res) {
							console.log(res.authSetting['scope.userFuzzyLocation'])
							if (res.authSetting['scope.userFuzzyLocation']) {
								that.getLocation(1);
							} else {
								uni.showToast({
									title: '授权失败',
									icon: 'none',
									mask: true
								});

							}
						}
					});
				}
			},
			ensure() {
				uni.showLoading({
					title: '加载中',
					mask: true
				})

				this.setUserLocation(this.cityTure).then(res => {
					uni.hideLoading();
					if (this.isText == 0) {
						uni.navigateTo({
							url: '/package/category/index'
						});
					} else if (this.isText == 1) {
						uni.switchTab({
							url: '/pages/index/index'
						});
					} else if (this.isText == 2) {
						let pages = getCurrentPages();
						let prevPage = pages[pages.length - 2];
						prevPage.onShow(true);
						uni.navigateBack();
					} else if (this.isText == 3) {
						if (this.user && this.user.communityList && this.user.communityList.length != 0) {
							for (let i = 0; i < this.user.communityList.length; i++) {
								let item = this.user.communityList[i];
								if (this.cityTure == item.communityName) {
									let pages = getCurrentPages();
									let prevPage = pages[pages.length - 2];
									prevPage.onShow(true);
									uni.navigateBack();
									return;
								}
							}
							uni.navigateTo({
								url: '/package/category/index'
							});
						} else {
							uni.navigateTo({
								url: '/package/category/index'
							});
						}

					} else if (this.isText == 5) {

						let isPass = false;
						let communityId = this.location.communityId
						this.user.communityList.forEach(item => {
							if (communityId == item.communityId) {
								isPass = true

								let expireTime = new Date(item.expireTime).getTime();
								let nowTime = new Date().getTime();
								let chaTime = expireTime - nowTime;
								if (this.pastTime >= chaTime) {
									// 已过期 即将过期
									uni.navigateTo({
										url: `/package/payment/index?buyType=30&communityId=${this.location.communityId}&priceId=${this.priceId}&informationTitle=${this.location.name}加购福利价&url=/pages/index/index&isComCode=true`
									});
								} else {
									// 未过期
									uni.showToast({
										title: '该社区已加入,请更换城市',
										icon: 'none',
										mask: true,
									});

								}
							}
						})
						if (!isPass) {
							uni.navigateTo({
								url: `/package/payment/index?buyType=30&communityId=${this.location.communityId}&priceId=${this.priceId}&informationTitle=${this.location.name}加购福利价&url=/pages/index/index&isComCode=true`
							});
						}



					}




				})

			},
			changIndex(oneIndex, twoIndex, name) {
				this.listIndex = [oneIndex, twoIndex];
				this.cityTure = name;

			},
			goBlack() {
				uni.navigateBack();
			}
		}
	}
</script>
<style lang="scss" scoped>
	.pages_intelligence {
		background-color: #F0F0F0;
		min-height: 100vh;
		box-sizing: border-box;

		.ensureButton {
			width: 558rpx;
			height: 88rpx;
			line-height: 88rpx;
			background: #FFDA2D;
			opacity: 1;
			border-radius: 24rpx;
			font-size: 28rpx;
			font-family: 蘋方-簡;
			font-weight: normal;
			color: #000000;
			text-align: center;
			margin: 48rpx auto;
			position: fixed;
			bottom: 0%;
			z-index: 9;
			left: 50%;
			transform: translateX(-50%);
		}

		.noEnsureButton {
			width: 558rpx;
			height: 88rpx;
			line-height: 88rpx;
			background: #efefef;
			opacity: 1;
			border-radius: 24rpx;
			font-size: 28rpx;
			font-family: 蘋方-簡;
			font-weight: normal;
			color: #999;
			text-align: center;
			margin: 48rpx auto;
			position: fixed;
			bottom: 0%;
			left: 50%;
			transform: translateX(-50%);
		}

		.indexListBox {
			overflow: scroll;

		}

		/deep/.u-index-list {
			padding-bottom: 150rpx;
		}

		/deep/.u-index-list__letter {
			display: none;
		}

		/deep/.u-index-anchor {
			background-color: #f7f7f7 !important;
			color: #999999 !important;
		}

		/deep/.list-cell {
			background-color: #fff;
			height: 104rpx;
			line-height: 104rpx;
			padding: 0 32rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			position: relative;

		}

		.list-cell:not(:last-child) {
			&::after {
				content: '';
				width: 90%;
				height: 1rpx;
				background: #eaeaea;
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);

			}
		}

		/deep/.listAct {
			background-color: #fffbe9;

			image {
				width: 40rpx;
				height: 40rpx;
			}
		}

		/deep/.u-index-item {
			width: 100% !important;
			background: #fff;
		}

		/deep/.u-border-bottom {
			border: none !important;
		}

		.cityHeard_bottonBox {
			display: flex;
			justify-content: space-between;
		}

		.cityHeard_bottonBoxLeft {
			height: 40rpx;
			font-size: 28rpx;
			font-family: PingFang SC;
			font-weight: 400;
			line-height: 40rpx;
			color: #333333;
		}

		.cityHeard_bottonBoxRight {
			display: flex;
			align-content: center;

			span {
				height: 40rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 400;
				line-height: 40rpx;
				color: #333333;
			}

			image {
				width: 40rpx;
				height: 40rpx;
			}
		}

		.cityBox {
			position: absolute;
			left: 0;
			width: 100%;
		}

		.cityHeard {
			width: 100%;
			padding: 32rpx;
			box-sizing: border-box;
			width: 100%;
			background-color: #fff;

		}

		.cityHeard_title {
			height: 50rpx;
			font-size: 36rpx;
			font-family: PingFang SC;
			font-weight: bold;
			line-height: 50rpx;
			color: #000000;
			margin-bottom: 8rpx;
		}

		.cityHeard_text {
			font-size: 24rpx;
			font-family: PingFang SC;
			font-weight: 400;
			line-height: 34rpx;
			color: #999999;
		}

		.cityHeard_input {
			width: 686rpx;
			height: 88rpx;
			line-height: 88rpx;
			background: #f7f7f7;
			border: 2rpx solid #EFEFEF;
			opacity: 1;
			border-radius: 16rpx;
			font-family: PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
			color: #999;
			text-align: center;
			margin: 32rpx 0;
		}
	}
</style>
